<template>
  <view class="container">
    <cover-view class="content-nav-bg">
      <cover-view class="search-box">
        <cover-view class="switch-left" @click="navClick">
          <cover-image src="@/static/back.png" style="width: 50rpx; height: 50rpx;"></cover-image>
        </cover-view>
        <cover-view class="switch">
          <cover-view class="list" @click="tapType">音频</cover-view>
          <cover-view class="list on">视频</cover-view>
        </cover-view>
        <cover-view></cover-view>
      </cover-view>
    </cover-view>
    <!-- 相机组件，占满整个屏幕 -->
    <camera
      v-if="!isPreview"
      ref="cameraRef"
      id="camera"
      :device-position="cameraPosition"
      :output-dimension="outputDimension"
      flash="off"
      class="camera"
      @error="onCameraError"
    ></camera>
    <!-- 视频预览组件 -->
    <video
      v-else
      class="camera"
      id="previewVideo"
      :src="videoPath"
      controls
      @error="onVideoError"
      @timeupdate="timeupdate"
    ></video>
    <!-- 底部控制区域 -->
    <cover-view class="control-panel">
      <!-- 左侧收起按钮 -->
      <cover-view class="control-btn" @click="leftButtonAction">
        <cover-view class="icon" v-if="isPreview">
          <cover-image src="@/static/icon/p1.png" style="width: 60rpx; height: 60rpx;"></cover-image>
        </cover-view>
        <cover-view class="btn-text" v-if="isPreview">{{ leftButtonText }}</cover-view>
      </cover-view>

      <!-- 中间录制控制按钮 -->
      <cover-view class="record-btn-container">
        <!-- <view 
            class="record-btn" 
            :class="recording ? 'recording' : ''" 
            @click="middleButtonAction">
          </view> -->
        <cover-view class="icon" @click="middleButtonAction">
          <cover-image src="@/static/icon/p2.png" style="width: 80rpx; height: 80rpx;"></cover-image>
        </cover-view>
        <cover-view class="record-time">
          <cover-view v-if="!isRecording && !isPreview">{{ middleButtonText }}</cover-view>
          <cover-view v-if="isRecording" class="recording-time">
            {{ formatTime(recordingTime) }}
          </cover-view>
          <cover-view v-if="isPreview" class="recording-time">{{ formatVideoTime() }}</cover-view>
        </cover-view>
      </cover-view>

      <!-- 右侧翻转摄像头按钮 -->
      <cover-view class="control-btn" @click="rightButtonAction">
        <cover-view class="icon">
          <cover-image src="@/static/icon/p3.png" style="width: 60rpx; height: 60rpx;" v-if="isPreview"></cover-image>
          <cover-image src="@/static/icon/p4.png" style="width: 60rpx; height: 60rpx;" v-else></cover-image>
        </cover-view>
        <cover-view class="btn-text">{{ rightButtonText }}</cover-view>
      </cover-view>
    </cover-view>

    <!-- 半透明遮罩层 -->
    <!-- <view class="overlay"></view> -->

    <!-- 顶部状态栏占位 -->
    <view class="status-bar"></view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cameraPosition: 'back',
      isRecording: false,
      isPreview: false,
      recordingTime: 0,
      previewTime: 0,
      videoPath: '',
      timer: null,
      flashMode: 'off',
      // 按钮文本状态
      leftButtonText: '收起',
      middleButtonText: '开始录制',
      rightButtonText: '翻转',
      cameraContext: null
    }
  },
  onUnload() {
    // 页面卸载时清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    tapType() {
      this.$emit('change', 'record')
    },
    navClick() {
      uni.navigateBack()
    },
    // 格式化时间为 MM:SS 格式
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    formatVideoTime() {
      return `${this.formatTime(this.recordingTime - this.previewTime)}`
    },
    timeupdate(event) {
      this.previewTime = parseInt(event.detail.currentTime)
    },

    // 左侧按钮动作
    leftButtonAction() {
      if (this.isPreview) {
        // 预览状态下点击"重录"
        this.resetRecorder()
      } else {
        // 录制状态下点击"收起"（无功能）
        console.log('收起功能未实现')
      }
    },

    // 中间按钮动作
    middleButtonAction() {
      if (this.isPreview) {
        // 预览状态下点击"视频试看"
        this.playVideo()
      } else if (this.isRecording) {
        // 录制中点击"完成录制"
        if (this.recordingTime < 120) {
          this.$refs.uToast.show({
            type: 'default',
            message: '至少录制120秒',
            duration: 3000
          })
          return
        }
        this.stopRecording()
      } else {
        // 未录制点击"开始录制"
        this.startRecording()
      }
    },

    // 右侧按钮动作
    rightButtonAction() {
      if (this.isPreview) {
        // 预览状态下点击"完成"
        this.uploadVideo()
      } else {
        // 录制状态下点击"翻转"
        this.switchCamera()
      }
    },

    // 开始录制
    startRecording() {
      this.cameraContext = uni.createCameraContext()
      this.isRecording = true
      this.middleButtonText = '完成录制'

      // 开始录制
      this.cameraContext.startRecord({
        quality: 'normal',
        timeout: 300,
        selfieMirror: false,
        success: () => {
          // 开始计时
          this.recordingTime = 0
          this.timer = setInterval(() => {
            this.recordingTime++
          }, 1000)
          console.log('开始录制')
        },
        fail: (err) => {
          console.error('录制失败:', err)
          uni.showToast({
            title: '录制失败，请重试',
            icon: 'none'
          })
          this.resetRecorder()
        }
      })
    },

    // 停止录制
    stopRecording() {
      // const cameraContext = uni.createCameraContext()
      clearInterval(this.timer)
      // 停止录制
      this.cameraContext.stopRecord({
        success: (res) => {
          // 停止计时器
          this.timer = null
          this.videoPath = res.tempVideoPath
          this.isRecording = false
          this.isPreview = true

          // 更新按钮状态
          this.leftButtonText = '重录'
          this.middleButtonText = '视频试看'
          this.rightButtonText = '完成'

          console.log('录制完成:', this.videoPath)
        },
        fail: (err) => {
          console.error('停止录制失败:', err)
          uni.showToast({
            title: '停止录制失败，请重试',
            icon: 'none'
          })
          this.resetRecorder()
        }
      })
    },

    // 重置录制器
    resetRecorder() {
      // 清除计时器
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }

      // 重置状态
      this.isRecording = false
      this.isPreview = false
      this.recordingTime = 0
      this.previewTime = 0

      // 更新按钮状态
      this.leftButtonText = '收起'
      this.middleButtonText = '开始录制'
      this.rightButtonText = '翻转'
    },

    playVideo() {
      const cameraContext = uni.createVideoContext('previewVideo', this)
      cameraContext.play()
    },

    // 切换前后摄像头
    switchCamera() {
      this.cameraPosition = this.cameraPosition === 'back' ? 'front' : 'back'
    },
    // 上传视频
    async uploadVideo() {
      this.$emit('end', this.videoPath)
    },

    // 相机错误处理
    onCameraError(err) {
      console.error('相机错误:', err)
      uni.showToast({
        title: '相机启动失败，请检查权限',
        icon: 'none'
      })
    },

    // 视频错误处理
    onVideoError(err) {
      console.error('视频错误:', err)
      uni.showToast({
        title: '视频播放失败',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.camera {
  width: 100%;
  height: 100%;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 2;
  pointer-events: none;
}

.status-bar {
  height: var(--status-bar-height);
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 3;
}

.camera-view-box {
  position: relative;
}

.control-panel {
  position: fixed;
  bottom: 40rpx;
  left: 0;
  width: 100%;
  height: 150rpx;
  // background-color: rgba(0, 0, 0, 0.4);
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.control-btn {
  width: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
  }
}

.btn-text {
  color: white;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.record-btn-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  .icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
  }
}

.record-btn {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #ff3b30;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.record-btn.recording {
  width: 100rpx;
  height: 100rpx;
  border-radius: 20rpx;
}

.record-btn text {
  color: white;
  font-size: 28rpx;
}

.record-time {
  color: white;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.content-nav-bg {
  position: fixed;
  z-index: 10;
  width: 100%;
  top: 100rpx;
  .search-box{
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .switch {
    display: flex;
    width: 200rpx;
    height: 60rpx;
    background-color: #ababab;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    .list {
      flex: 1;
      text-align: center;
      height: 100%;
      border-radius: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 60rpx;
      color: #fff;
      &.on {
        background-color: #fff;
        color: #fc7110;
      }
    }
  }
  .shi-ju {
    display: flex;
    justify-content: center;
    padding-top: 40rpx;
  }
  .lu-bg {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 20vh;
    .btn {
      width: 150rpx;
      height: 150rpx;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0px 0px 5px #cfcfcf;
    }
    .txt {
      margin-top: 20rpx;
      color: #666;
    }
  }
  .btn-area {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
</style>
